﻿using System;
using System.Linq;
using System.IO;
using System.Xml;
using System.Collections;
using System.Configuration;
using System.Globalization;

namespace Oxage.Common
{
	public partial class Config
	{
		#region Constants
		private const string CONFIG_ENTRY_XPATH = "//Configuration//Region[@Path='{0}']//Entry[@Key='{1}']";
		private const string CONFIG_REGION_XPATH = "//Configuration//Region[@Path='{0}']";
		private const string CONFIG_DEFAULT_REGISTY_PATH = @"Software\Oxage\Common\";
		#endregion

		#region Members
		private static int? languageId = null;
		private static bool defaultCache = false;
		private static string registryRootPath = CONFIG_DEFAULT_REGISTY_PATH; //TODO: Set HKEY root
		private static ConfigSource defaultSource = ConfigSource.Registry;
		private static Hashtable htCache = new Hashtable(); //Cached variables
		private static XmlDocument xmlCache = null; //Cached xml config file
		#endregion

		#region Properties
		/// <summary>
		/// Gets or sets the flag that defines if variable is cached by default (if not explicitly specified).
		/// </summary>
		public static bool DefaultCache
		{
			get { return defaultCache; }
			set { defaultCache = value; }
		}

		/// <summary>
		/// Gets or sets the property that defines default ConfigSource (if not explicitly specified).
		/// </summary>
		public static ConfigSource DefaultSource
		{
			get { return defaultSource; }
			set { defaultSource = value; }
		}

		/// <summary>
		/// Gets or sets a registry root path.
		/// </summary>
		public static string RegistryRootPath
		{
			get
			{
				return registryRootPath;
			}
			set
			{
				if (!string.IsNullOrEmpty(value))
				{
					if (!value.EndsWith("\\"))
					{
						value += "\\";
					}
					registryRootPath = value;
				}
			}
		}
		#endregion

		#region Getters
		public static string Get(string key)
		{
			string value = null;
			Get(key, out value, defaultCache, defaultSource);
			return value;
		}

		public static bool Get(string key, out string value)
		{
			return Get(key, out value, defaultCache, defaultSource);
		}

		public static bool Get(string key, out string value, bool cache, ConfigSource source)
		{
			value = null;
			bool completed = false;

			//Sample: Shop\Articles\Count -> path = "Shop\Articles", pkey = "Count"
			string path = Path.GetDirectoryName(key);
			string pkey = Path.GetFileName(key); //Parsed key

			switch (source)
			{
				case ConfigSource.AppConfig:
					#region App.config
					if (cache)
					{
						if (htCache.Contains(key))
						{
							value = (string)htCache[key];
							completed = true;
						}
						else
						{
							value = ConfigurationManager.AppSettings[key];
							htCache.Add(key, value);
							completed = true;
						}
					}
					else
					{
						value = ConfigurationManager.AppSettings[key];
						completed = true;
					}
					#endregion
					break;

				case ConfigSource.Registry:
					#region Registry
					if (cache)
					{
						//If cache contains key
						if (htCache.Contains(key))
						{
							value = (string)htCache[key];
							completed = true;
						}
						else
						{
							Microsoft.Win32.RegistryKey reg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(RegistryRootPath + path);
							if (reg != null)
							{
								value = (string)reg.GetValue(pkey);
								reg.Close();
								htCache.Add(key, value); //Note that htCache contains key not pkey
								completed = true;
							}
						}
					}
					else
					{
						Microsoft.Win32.RegistryKey reg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(RegistryRootPath + path);
						if (reg != null)
						{
							value = (string)reg.GetValue(pkey);
							reg.Close();
							completed = true;
						}
					}
					#endregion
					break;

				case ConfigSource.Xml:
					#region XmlDocument
					if (xmlCache != null)
					{
						if (cache)
						{
							if (htCache.Contains(key))
							{
								value = (string)htCache[key];
								completed = true;
							}
							else
							{
								string xpath = string.Format(CONFIG_ENTRY_XPATH, path, pkey);
								XmlNode node = xmlCache.SelectSingleNode(xpath);
								if (node != null)
								{
									value = (node.Attributes["Value"] != null ? node.Attributes["Value"].Value : null);
									htCache.Add(pkey, value);
									completed = true;
								}
							}
						}
						else
						{
							string xpath = string.Format(CONFIG_ENTRY_XPATH, path, pkey);
							XmlNode node = xmlCache.SelectSingleNode(xpath);
							if (node != null)
							{
								value = (node.Attributes["Value"] != null ? node.Attributes["Value"].Value : null);
								completed = true;
							}
						}
					}
					#endregion
					break;
			}

			return completed;
		}

		public static bool Get(string key, out int value)
		{
			string temp = null;
			bool parsed = Get(key, out temp);
			bool converted = int.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out int value, bool cache, ConfigSource source)
		{
			string temp = null;
			bool parsed = Get(key, out temp, cache, source);
			bool converted = int.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out long value)
		{
			string temp = null;
			bool parsed = Get(key, out temp);
			bool converted = long.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out long value, bool cache, ConfigSource source)
		{
			string temp = null;
			bool parsed = Get(key, out temp, cache, source);
			bool converted = long.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out double value)
		{
			string temp = null;
			bool parsed = Get(key, out temp);
			bool converted = double.TryParse(temp, NumberStyles.Any, CultureInfo.InvariantCulture, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out double value, bool cache, ConfigSource source)
		{
			string temp = null;
			bool parsed = Get(key, out temp, cache, source);
			bool converted = double.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out bool value)
		{
			string temp = null;
			bool parsed = Get(key, out temp);
			bool converted = bool.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out bool value, bool cache, ConfigSource source)
		{
			string temp = null;
			bool parsed = Get(key, out temp, cache, source);
			bool converted = bool.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get<TEnum>(string key, out TEnum value) where TEnum : struct
		{
			return Get<TEnum>(key, out value, DefaultCache, DefaultSource);
		}

		public static bool Get<TEnum>(string key, out TEnum value, bool cache, ConfigSource source) where TEnum : struct
		{
			value = default(TEnum);
			string temp = null;
			bool parsed = Get(key, out temp);
			bool converted = false;
			if (temp != null && typeof(Enum).IsAssignableFrom(typeof(TEnum)) && Enum.IsDefined(typeof(TEnum), temp))
			{
				//Only if value is enum
				value = (TEnum)Enum.Parse(typeof(TEnum), temp);
				converted = true;
			}
			return parsed && converted;
		}

		public static bool Get(string key, out TimeSpan value)
		{
			string temp = null;
			bool parsed = Get(key, out temp);
			bool converted = TimeSpan.TryParse(temp, out value);
			return parsed && converted;
		}

		public static bool Get(string key, out TimeSpan value, bool cache, ConfigSource source)
		{
			string temp = null;
			bool parsed = Get(key, out temp, cache, source);
			bool converted = TimeSpan.TryParse(temp, out value);
			return parsed && converted;
		}
		#endregion

		#region Setters
		public static void Set(string key, string value)
		{
			Set(key, value, defaultCache, defaultSource);
		}

		public static void Set(string key, string value, bool cache, ConfigSource source)
		{
			string path = Path.GetDirectoryName(key);
			string pkey = Path.GetFileName(key);

			switch (source)
			{
				case ConfigSource.AppConfig:
					break;

				case ConfigSource.Registry:
					#region Registry
					Microsoft.Win32.RegistryKey reg = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(RegistryRootPath + path);
					if (reg != null)
					{
						reg.SetValue(pkey, value);
						reg.Close();
					}
					#endregion
					break;

				case ConfigSource.Xml:
					#region XmlDocument
					if (xmlCache != null)
					{
						//Create xpath to check if entry with the same key already exists
						string xpath = string.Format(CONFIG_ENTRY_XPATH, path, pkey);
						XmlNode node = xmlCache.SelectSingleNode(xpath);

						//Update existing node
						if (node != null)
						{
							if (node.Attributes["Value"] != null)
							{
								//Update Value attribute
								node.Attributes["Value"].Value = value;
							}
							else
							{
								//Insert Value attribute
								XmlAttribute valueAttribute = xmlCache.CreateAttribute("Value");
								valueAttribute.Value = value;
								node.Attributes.Append(valueAttribute);
							}
						}
						//Create a new node
						else
						{
							xpath = string.Format(CONFIG_REGION_XPATH, path);
							node = xmlCache.SelectSingleNode(xpath);

							//If region node is missing
							if (node == null)
							{
								node = xmlCache.CreateElement("Region");
								XmlAttribute pathAttribute = xmlCache.CreateAttribute("Path");
								pathAttribute.Value = path;
								node.Attributes.Append(pathAttribute);
								xmlCache.AppendChild(node);
							}

							//Append Entry node
							XmlElement entry = xmlCache.CreateElement("Entry");
							entry.SetAttribute("Key", pkey);
							entry.SetAttribute("Value", value);
							node.AppendChild(entry);
						}
					}
					#endregion
					break;
			}

			//Save to cache
			if (cache)
			{
				if (htCache.Contains(key))
				{
					htCache[key] = value;
				}
				else
				{
					htCache.Add(key, value);
				}
			}
		}

		public static void Set(string key, int value)
		{
			Set(key, value.ToString());
		}

		public static void Set(string key, int value, bool cache, ConfigSource source)
		{
			Set(key, value.ToString(), cache, source);
		}

		public static void Set(string key, double value)
		{
			Set(key, value.ToString());
		}

		public static void Set(string key, double value, bool cache, ConfigSource source)
		{
			Set(key, value.ToString(CultureInfo.InvariantCulture), cache, source);
		}

		public static void Set(string key, bool value)
		{
			Set(key, value.ToString());
		}

		public static void Set(string key, bool value, bool cache, ConfigSource source)
		{
			Set(key, value.ToString(), cache, source);
		}

		public static void Set(string key, TimeSpan value)
		{
			Set(key, value.ToString());
		}

		public static void Set(string key, TimeSpan value, bool cache, ConfigSource source)
		{
			Set(key, value.ToString(), cache, source);
		}

		public static void Set<T>(string key, T value)
		{
			if (value != null)
			{
				Set(key, value.ToString());
			}
			else
			{
				Clear(key);
			}
		}

		public static void Set<T>(string key, T value, bool cache, ConfigSource source)
		{
			if (value != null)
			{
				Set(key, value.ToString(), cache, source);
			}
			else
			{
				Clear(key, source);
			}
		}
		#endregion

		#region Cleaners
		public static void Clear(string key)
		{
			Clear(key, defaultSource);
		}

		public static void Clear(string key, ConfigSource source)
		{
			string path = Path.GetDirectoryName(key);
			string pkey = Path.GetFileName(key); //Parsed key

			switch (source)
			{
				case ConfigSource.AppConfig:
					break;

				case ConfigSource.Registry:
					#region Registry
					try
					{
						Microsoft.Win32.RegistryKey reg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(RegistryRootPath + path, true);
						if (reg != null && reg.GetValue(pkey) != null)
						{
							reg.DeleteValue(pkey);
							reg.Close();
						}
					}
					catch
					{
						//Exception if key does not exist
					}
					#endregion
					break;
			}
		}

		public static void ClearCache()
		{
			htCache = new Hashtable();
		}
		#endregion

		#region Exists
		public static bool Exists(string key, ConfigSource source)
		{
			string value = null;
			bool completed = false;

			//Sample: Shop\Articles\Count -> path = "Shop\Articles", pkey = "Count"
			string path = Path.GetDirectoryName(key);
			string pkey = Path.GetFileName(key); //Parsed key

			switch (source)
			{
				case ConfigSource.AppConfig:
					#region App.config
					value = ConfigurationManager.AppSettings[key];
					completed = (value != null);
					#endregion
					break;

				case ConfigSource.Registry:
					#region Registry
					Microsoft.Win32.RegistryKey reg = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(RegistryRootPath + path);
					if (reg != null)
					{
						value = (string)reg.GetValue(pkey);
						reg.Close();
						completed = (value != null);
					}
					#endregion
					break;

				case ConfigSource.Xml:
					#region XmlDocument
					//Not implemented
					#endregion
					break;
			}

			//TODO: Delete from cache

			return completed;
		}
		#endregion

		#region Methods
		public static void ImportXmlConfig(string path)
		{
			XmlDocument doc = new XmlDocument();
			doc.Load(path);
			if (doc.DocumentElement.LocalName == "Configuration")
			{
				xmlCache = doc;
			}
		}

		public static void ImportXmlConfig(XmlDocument doc)
		{
			if (doc != null && doc.DocumentElement.LocalName == "Configuration")
			{
				xmlCache = doc;
			}
		}

		public static void ExportXmlConfig(string path)
		{
			if (xmlCache != null)
			{
				xmlCache.Save(path);
			}
		}
		#endregion

		#region Samples
		public static void Sample()
		{
			//Sample #1
			Config.DefaultCache = true; //Cache automatically
			Config.DefaultSource = ConfigSource.Registry; //Read/write to registry

			//Sample #2
			string path = null;
			Config.Get("Path", out path); //Read Path entry from registry

			//Sample #3
			TimeSpan syncTime = TimeSpan.Zero;
			Config.Get("SyncTime", out syncTime, false, ConfigSource.AppConfig); //Read SyncTime entry from AppConfig

			//Sample #4
			Config.Set("Flag", true); //Set Flag to true in registry

			//Sample #5
			Config.Clear("Flag"); //Delete Flag entry from registry

			//Sample #6
			Config.ImportXmlConfig(@"D:\Temp\Config.xml");
			Config.Set(@"Common\Path", @"D:\inetpub\www\project\", false, ConfigSource.Xml); //Path key in Common folder
			Config.ExportXmlConfig(@"D:\Temp\Config.xml");

			//Sample #7
			Config.Clear("Flag"); //Delete Flag entry from registry

			//Sample #8
			int count = 0;
			Config.Get(@"Shop\Articles\Count", out count, true, ConfigSource.Registry); //Get Count key from Shop\Articles from cache if possible or registry folder if does not exist in cache
		}
		#endregion
	}

	public enum ConfigSource
	{
		/// <summary>
		/// Configuration from app.config file, appSettings section.
		/// </summary>
		AppConfig = 1,
		/// <summary>
		/// Configuration from Windows Registry, path defined in RegistryRootPath property.
		/// </summary>
		Registry = 2,
		/// <summary>
		/// Configuration from in-memory XML document.
		/// </summary>
		Xml = 3,
	}
}
